<template>
    <!-- 联系人界面 -->
    <Layout>
        <template #left-content>
            <!-- 用于拖动窗口的控件 -->
            <div class="drag-panel drag"></div>
            <div class="top-search">
                <!-- 搜索 -->
                <el-input clearable placeholder="搜索" v-model="searchKey" size="small" @keyup="search">
                    <template #suffix>
                        <span class="iconfont icon-sousuo">
                        </span>
                    </template>
                </el-input>
            </div>
            <div class="contact-list" v-show="!searchKey">
                <template v-for="(item, index) in partList" :key="index">
                    <div class="part-title">{{ item.partName }}</div>
                    <!-- 左侧的组件 -->
                    <!-- 默认存在的控件 -->
                    <div class="part-list">
                        <!-- active使得控件样式为被选中，样式和内容由对象属性动态获取 -->
                        <div v-for="(sub, index) in item.children" :key="index"
                            :class="['part-item', sub.path == route.path ? 'active' : '']" @click="partJump(sub)">
                            <div :class="['iconfont', sub.icon]" :style="{ background: sub.iconBgColor }"></div>
                            <div class="text">{{ sub.name }}</div>
                            <!-- 申请信息处会显示申请信息数量 -->
                            <Badge :count="messageCountStore.getCount(sub.countKey)" :top="3" :left="45"></Badge>
                        </div>
                    </div>
                    <!-- 需要获取数据的控件 -->
                    <div v-for="(contact, index) in item.contactData" :key="index">
                        <!-- 好友或群聊的名片，选中会加深颜色，点击会展示详情（路由） -->
                        <div :class="['part-item', contact[contact.contactType == 'USER' ? 'userId' : 'groupId'] == route.query.contactId ? 'active' : '']"
                            @click="contactDetail(contact, item)">
                            <!-- 头像 -->
                            <Avatar :userId="contact[contact.contactType == 'USER' ? 'userId' : 'groupId']" :width="35">
                            </Avatar>
                            <!-- 名字 -->
                            <div class="text"> {{ contact[contact.contactType == 'USER' ? 'userName' : 'groupName'] }}
                            </div>
                        </div>
                    </div>
                    <!-- 如果没有数据则输出提示 -->
                    <div class="no-data" v-if="item.contactData && item.contactData.length == 0">
                        {{ item.emptyMsg }}
                    </div>
                </template>
            </div>
            <div class="search-list" v-show="searchKey">
                <ContactSearchResult :data="item" v-for="(item, index) in searchList" :key="index"
                    @click="searchClickHandler(item)">
                </ContactSearchResult>
            </div>
        </template>
        <template #right-content>
            <!-- 用于拖动窗口的控件 -->
            <div class="title-panel drag">{{ rightTitle }}</div>
            <!-- 下面Component的写法和直接写 <router-view></router-view> 效果相同，只是下面的写法可以有更多功能，如使用keep-alive标签-->
            <router-view v-slot="{ Component }">
                <component :is="Component" ref="component"></component>
            </router-view>
        </template>
    </Layout>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue"
const { proxy } = getCurrentInstance();

const formData = ref({});
const formDataRef = ref();
const rules = {
    title: [{ required: true, message: "请输入内容" }],
};

import { useMessageCountStore } from "@/stores/MessageCountStore";
const messageCountStore = useMessageCountStore();

const rightTitle = ref('');

/* 左侧框里的内容 */
const partList = ref([
    {
        partName: '新朋友',
        children: [
            {
                name: '搜索好友/群聊',
                icon: 'icon-sousuo1',
                iconBgColor: '#d4913b',
                showTitle: true,
                path: '/contact/search'
            },
            {
                name: '申请信息',
                icon: 'icon-add-friend',
                iconBgColor: '#7ac37a',
                path: '/contact/contactApply',
                showTitle: true,
                countKey: 'contactApplyCount'
            }
        ]
    },
    /* 下面的内容需要获取数据后填充 */
    {
        partName: '我的群聊',
        children: [
            {
                name: '新建群聊',
                icon: 'icon-chuangjianqunliao',
                iconBgColor: '#5cb5bd',
                showTitle: true,
                path: '/contact/createGroup'
            }
        ],
        showTitle: true,
        contactData: [],
        contactPath: '/contact/groupDetail'
    },
    {
        partName: '我加入的群聊',
        showTitle: true,
        contactData: [],
        contactPath: '/contact/groupDetail',
        emptyMsg: '暂未加入群聊'
    },
    {
        partName: '我的好友',
        children: [],
        showTitle: true,
        contactData: [],
        contactPath: '/contact/userDetail',
        emptyMsg: '暂无好友'
    }
]);

import ContactSearchResult from "./ContactSearchResult.vue";

const searchKey = ref("");
const searchList = ref([]);
const search = () => {
    searchList.value = [];
    if (!searchKey.value) {
        return;
    }
    const regex = new RegExp("(" + searchKey.value + ")", "ig");  //  g：表示全局（global）模式，即模式将被应用于所有字符串，而非在发现第一个匹配项时立即停止；i：表示不区分大小写（case-insensitive）模式，即在确定匹配项时忽略模式与字符串的大小写
    // 先找出全部联系人
    let allContactList = [];
    partList.value.forEach(item => {
        if (item.contactData) {
            allContactList = allContactList.concat(item.contactData);
        }
    });
    allContactList.forEach(item => {
        const searchName = item.userName || item.groupName;
        const searchId = item.userId || item.groupId;
        if (searchName.includes(searchKey.value)) {
            let newData = Object.assign({}, item);
            newData.searchName = searchName.replace(regex, "<span class='highlight'>" + searchKey.value + "</span>");
            newData.searchId = searchId;
            searchList.value.push(newData);
        }
    });
};

const searchClickHandler = (item) => {
    searchKey.value = "";
    // 前往聊天界面
    router.push({
        path: "/chat",
        query: {
            chatId: item.searchId,
            timestamp: new Date().getTime()
        }
    });
};

/* 点击后的路由跳转方法 */
const partJump = (item) => {
    if (item.showTitle) {
        rightTitle.value = item.name;
    }
    else {
        rightTitle.value = null;
    }
    // 如果点击的是申请信息界面，需要去掉消息提醒的气泡
    if (item.countKey) {
        messageCountStore.setCount(item.countKey, 0, true);
        myApi.updateContactNoReadCount(null);  // 传递null表示清空
    }
    router.push(item.path);
};

/* 获取好友或加入的群聊的信息 */
const loadContact = async (contactType) => {
    let result = await proxy.Request({
        method: "get",
        url: proxy.Api.loadContact,
        params: {
            contactType: contactType
        }
    })
    if (!result) {
        return;
    }
    if (contactType == "GROUP") {
        // 群聊
        partList.value[2].contactData = result.data;
    }
    else {
        // 好友
        partList.value[3].contactData = result.data;
    }
}
// 初始化要获取
loadContact("GROUP");
loadContact("USER");

/* 加载自己创建的群聊 */
const loadMyGroupInfo = async () => {
    let result = await proxy.Request({
        method: "get",
        url: proxy.Api.loadMyGroupInfo,
        showLoading: false
    })
    if (!result) {
        return;
    }
    partList.value[1].contactData = result.data;
}
loadMyGroupInfo();

/* 监听状态变化 */
import { useContactStateStore } from "@/stores/ContactStateStore";
const contactStateStore = useContactStateStore();
watch(() => contactStateStore.contactReload,
    (newVal, oldVal) => {
        if (!newVal) {
            return;
        }
        // 分情况刷新不同的数据
        switch (newVal) {
            case "GROUP":
                loadContact("GROUP");
                break;
            case "USER":
                loadContact("USER");
                break;
            case "MY_GROUP":
                loadMyGroupInfo();
                break;
            case "REMOVE_CONTACT":
                loadContact("USER");
                // 跳转到空白页
                router.push("/contact/blank");
                rightTitle.value = null;
                break;
            case "DISBAND_GROUP":
                loadMyGroupInfo();
                router.push("/contact/blank");
                rightTitle.value = null;
                break;
            case "LEAVE_GROUP":
                loadContact("GROUP");
                router.push("/contact/blank");
                rightTitle.value = null;
                break;
        }
    },
    { immediate: true, deep: true }
);

/* 点击好友/群聊组件时在右侧显示联系人详情 */
const contactDetail = (contact, item) => {
    // 上面的标题是名字
    if (item.showTitle) {
        rightTitle.value = contact[contact.contactType == 'USER' ? "userName" : "groupName"];
    }
    else {
        rightTitle.value = null;
    }
    // 路由切换右侧界面
    router.push({
        path: item.contactPath,
        query: {
            contactId: contact[contact.contactType == 'USER' ? "userId" : "groupId"]
        }
    })
}
</script>

<style lang="scss" scoped>
.drag-panel {
    height: 25px;
    background: #f7f7f7;
}

.top-search {
    padding: 0px 10px 9px 10px;
    background: #f7f7f7;
    display: flex;
    align-items: center;

    .iconfont {
        font-size: 12px;
    }
}

.contact-list {
    border-top: 1px solid #ddd;
    height: calc(89vh);
    overflow: hidden;

    &:hover {
        overflow: auto;
    }

    .part-title {
        color: #515151;
        padding-left: 10px;
        margin-top: 10px;
    }

    .part-list {
        border-bottom: 1px solid #d6d6d6;
    }

    .part-item {
        display: flex;
        align-items: center;
        padding: 10px 10px;
        position: relative;

        &:hover {
            cursor: pointer;
            background: #d6d6d7;
        }

        .iconfont {
            width: 35px;
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: #fff;
        }

        .text {
            flex: 1;
            color: #000000;
            margin-left: 10px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }

    .no-data {
        text-align: center;
        font-size: 12px;
        color: #9d9d9d;
        line-height: 30px;
    }

    .active {
        background: #c4c4c4;

        &:hover {
            background: #c4c4c4;
        }
    }
}

.title-panel {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    font-size: 18px;
    color: #000000;
}
</style>